package com.homework.servlet.admin;

import com.google.gson.Gson;
import com.homework.entity.User;
import com.homework.factory.ServiceFactory;
import com.homework.service.UserService;
import com.homework.servlet.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/admin/adminlogin.do")
public class LoginServlet extends BaseServlet {
    UserService userService= ServiceFactory.getUserService();

    public void adminlogin(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        User user = userService.loginMeneger(username, password);
        if (user==null){
            writer.write(new Gson().toJson("0"));
            //用户名或密码不能为空
            return;
        }
        req.getSession().setAttribute("user",user);
        writer.write(new Gson().toJson("1"));
    }

    public void adminKeepLogin(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        User user = (User)req.getSession().getAttribute("user");
        String username = user.getUsername();
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write(new Gson().toJson(username));
    }
}
